using System.Collections.Concurrent;
using WebRtcProject.Models;

namespace WebRtcProject.Services
{
    public class RoomService : IRoomService
    {
        private readonly ConcurrentDictionary<string, Room> _rooms = new();
        private readonly ILogger<RoomService> _logger;

        public RoomService(ILogger<RoomService> logger)
        {
            _logger = logger;
        }

        public async Task<Room> CreateRoomAsync(string roomName, int maxUsers = 10)
        {
            var room = new Room
            {
                Id = Guid.NewGuid().ToString(),
                Name = roomName,
                MaxUsers = maxUsers,
                CreatedAt = DateTime.UtcNow
            };

            _rooms[room.Id] = room;
            _logger.LogInformation("Created room {RoomId} with name {RoomName}", room.Id, roomName);

            return await Task.FromResult(room);
        }

        public async Task<Room?> GetRoomAsync(string roomId)
        {
            _rooms.TryGetValue(roomId, out var room);
            return await Task.FromResult(room);
        }

        public async Task<List<Room>> GetAllRoomsAsync()
        {
            return await Task.FromResult(_rooms.Values.ToList());
        }

        public async Task<bool> AddUserToRoomAsync(string roomId, User user)
        {
            if (!_rooms.TryGetValue(roomId, out var room))
            {
                _logger.LogWarning("Attempted to add user to non-existent room {RoomId}", roomId);
                return false;
            }

            if (room.IsFull)
            {
                _logger.LogWarning("Attempted to add user to full room {RoomId}", roomId);
                return false;
            }

            // 移除用户的旧房间关联
            if (!string.IsNullOrEmpty(user.RoomId))
            {
                await RemoveUserFromRoomAsync(user.RoomId, user.Id);
            }

            user.RoomId = roomId;
            room.Users.Add(user);
            
            _logger.LogInformation("Added user {UserId} to room {RoomId}", user.Id, roomId);
            return true;
        }

        public async Task<bool> RemoveUserFromRoomAsync(string roomId, string userId)
        {
            if (!_rooms.TryGetValue(roomId, out var room))
            {
                return false;
            }

            var user = room.Users.FirstOrDefault(u => u.Id == userId);
            if (user != null)
            {
                room.Users.Remove(user);
                user.RoomId = null;
                _logger.LogInformation("Removed user {UserId} from room {RoomId}", userId, roomId);

                // 如果房间为空，删除房间
                if (room.Users.Count == 0)
                {
                    await DeleteRoomAsync(roomId);
                }
                
                return true;
            }

            return false;
        }

        public async Task<bool> DeleteRoomAsync(string roomId)
        {
            if (_rooms.TryRemove(roomId, out var room))
            {
                _logger.LogInformation("Deleted room {RoomId}", roomId);
                return true;
            }

            return false;
        }

        public async Task<List<User>> GetRoomUsersAsync(string roomId)
        {
            if (_rooms.TryGetValue(roomId, out var room))
            {
                return await Task.FromResult(room.Users.ToList());
            }

            return await Task.FromResult(new List<User>());
        }
    }
} 